package com.wj.tool.common.bean.restful;

import com.wj.tool.common.utils.JsonUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description: 正常时处理类（系统正常运行时 返回restfulbody）
 * @create: 2021/1/14 10:03
 */

@RestControllerAdvice(
        annotations = {RestfulBody.class}
)
public class RestfulResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    public RestfulResponseBodyAdvice() {
    }

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType) || StringHttpMessageConverter.class.isAssignableFrom(converterType);
    }

    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return RestfulResponseUtils.successResponse();
        } else if (body instanceof String) {
            RestfulResponseBody responseBody = RestfulResponseUtils.successResponse(body, (String)null);
            return JsonUtils.objectToString(responseBody);
        } else {
            return RestfulResponseBody.class.isAssignableFrom(body.getClass()) ? body : RestfulResponseUtils.successResponse(body, (String)null);
        }
    }
}